'use strict';

var _koa = require('koa');

var _koa2 = _interopRequireDefault(_koa);

var _socket = require('socket.io');

var _socket2 = _interopRequireDefault(_socket);

var _index = require('./SQLmodules/index');

var _koaBody = require('koa-body');

var _koaBody2 = _interopRequireDefault(_koaBody);

var _main = require('./Routers/main');

var _main2 = _interopRequireDefault(_main);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { return step("next", value); }, function (err) { return step("throw", err); }); } } return step("next"); }); }; }

var app = new _koa2.default();
var server = require('http').Server(app.callback());
var io = new _socket2.default(server);

app.use(function () {
	var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee(ctx, next) {
		return regeneratorRuntime.wrap(function _callee$(_context) {
			while (1) {
				switch (_context.prev = _context.next) {
					case 0:
						return _context.abrupt('return', next().then(function () {
							ctx.body = ctx.body || {};
							ctx.body.ok = ctx.body.ok || 1;
							ctx.body['from'] = ctx.request.url;
						}, function (err) {
							ctx.body = {
								status: err.status,
								message: err.message
							};
						}));

					case 1:
					case 'end':
						return _context.stop();
				}
			}
		}, _callee, undefined);
	}));

	return function (_x, _x2) {
		return _ref.apply(this, arguments);
	};
}());

app.use((0, _koaBody2.default)({}));

app.use(function (ctx, next) {
	console.log("Request Url:" + ctx.request.url);
	if (ctx.request.method === 'GET') {
		ctx.request.body = ctx.request.query;
	}
	return next();
});

app.use(_main2.default.routes());

/*
io.on('connection', socket=>{
	console.log("here! someone connected!");
	socket.on('foo', data=>{
		console.log(data);
		setInterval(()=>socket.emit('bar', {text:"hi"}),1000);
	})
});*/

(0, _index.initMySql)().then(function () {
	console.log("Database Ok.");
	server.listen(3000);
});